package com.fable.common.config;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDateTime;

/**
 * @author 23086
 */
@Order
@Slf4j
@Component
public class CleanLogConfig implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) {
        cleanLog();
        log.info("------清理往期log-----");
    }

    public void cleanLog() {
        String logPath = System.getProperty("user.dir") + File.separator + "log" + File.separator;
        String[] infoAndError = {"error", "info"};
        String time = DateUtil.format(LocalDateTime.now(), DatePattern.NORM_DATE_PATTERN);
        for (String s : infoAndError) {
            File file = new File(logPath + s);
                if (file.exists()) {
                    File[] files = file.listFiles();
                    assert files != null;
                    for (File f : files) {
                        String[] strings = f.getName().split("\\.");
                        if (!strings[1].equals(time)) {
                            f.delete();
                        }
                    }
                }
            }
    }
}
